package com.sunseagear.wind.modules.test.twotable.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.http.RPage;
import com.sunseagear.common.base.mvc.controller.BaseBeanController;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.common.aspectj.annotation.Log;
import com.sunseagear.wind.common.aspectj.enums.LogType;
import com.sunseagear.wind.modules.test.twotable.entity.Car;
import com.sunseagear.wind.modules.test.twotable.service.ICarService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/test/twotable/car")
@Log(title = "车辆品牌分组")
@RequiredArgsConstructor
public class CarController extends BaseBeanController {

    private final ICarService carService;


    /**
     * 根据页码和每页记录数，以及查询条件动态加载数据
     */
    @PostMapping(value = "list")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("test:twotable:car:list")
    public RPage<Car> list(HttpServletRequest request) {
        //加入条件
        QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_date");
        String keyword = request.getParameter("keyword");
        if (!StringUtils.isEmpty(keyword)) {
            queryWrapper.like("name", keyword).or().like("code", keyword);
        }
        // 预处理
        Page<Car> pageBean = carService.page(getPage(), queryWrapper);
        return RPage.success(pageBean);
    }

    @GetMapping("detail/{id}")
    @Log(logType = LogType.SELECT)
    @SaCheckPermission("test:twotable:car:detail")
    public R<Car> detail(@PathVariable("id") Long id) {
        Car car = carService.getById(id);
        return R.success(car);
    }

    @PostMapping("add")
    @Log(logType = LogType.INSERT)
    @SaCheckPermission("add")
    public R<Void> add(@Validated Car entity) {
        carService.save(entity);
        return R.success("添加成功");
    }

    @PostMapping("update")
    @Log(logType = LogType.UPDATE)
    @SaCheckPermission("test:twotable:car:update")
    public R<Void> update(@Validated Car entity) {
        carService.saveOrUpdate(entity);
        return R.success("更新成功");
    }

    @PostMapping("delete")
    @SaCheckPermission("test:twotable:car:delete")
    public R<Void> delete(@RequestParam("ids") List<Long> idList) {
        carService.removeBatchByIds(idList);
        return R.success("删除成功");
    }

}
